import '../Scss/AnnexList.scss'

import axios from 'axios'
import dayjs from 'dayjs'

import * as flvjs from 'flv.js'
import { saveAs } from 'file-saver'
import { Editor } from '@tinymce/tinymce-react'
import { Player, BigPlayButton } from 'video-react'
import { useState, useEffect, useRef, useCallback } from 'react'
import { useEventEmitter, useBoolean, useRequest, useMount } from 'ahooks'
import {
    Result,
    Button,
    message,
    QRCode,
    Image,
    Tabs,
    Descriptions,
    Empty,
    Popconfirm,
    Table,
    List,
    Popover,
    Input,
    Select,
    DatePicker,
    Steps,
    Divider,
} from 'antd'

import { v4 } from 'uuid'
import { Http } from '../../Api'
import { ModalBox } from '../ModalBox'
import { API_LIST } from '../../Api/Api'
import Loading from '../../Currency/Loading'
import { initPrinter } from '../../Configure/Printer'
import { IndependenceUpload } from '../../Form/FormAssembly'
import { Video, DaHuaCameraPlayback } from '../../Configure/Video'
import { PrinterData, PictureStream } from '../../Configure/QRcode'
import { LiveBox } from '../../../Pages/Front/Common/Options/HLSSource'
import { project } from '../../Data'
import { WeChatConfig, WebCommonUrl } from '../../Configure/CommonParameter'
import { LoginSignUpGetUserInfo } from '../../Login/LoginFunc'

const { GC, ttxVideoAll, location } = window
GC.Spread.Common.CultureManager.culture('zh-cn')

const { TextArea } = Input

const fallback =
    ''

const tripartiteList = ['www.bilibili.com', 'v.qq.com']

const { client_id } = project[location.hostname]

const { appid, redirect_uri } = WeChatConfig

export const SecurityNewDetails = ({ data }) => {
    const [Data, setData] = useState()
    const [Details, setDetails] = useState()
    const { runAsync } = useRequest(Http, { manual: true })

    useMount(() => {
        runAsync({ url: 'getSecurityByUuid', data: { uuid: data.data.uuid } }).then(res => {
            setData(res.list[0])
            const data = res.list1.map(item => {
                const groupedData = item.children.reduce((acc, item) => {
                    if (!acc[item.Keyword]) acc[item.Keyword] = []
                    acc[item.Keyword].push(item)
                    return acc
                }, {})
                const Image1 = groupedData['1'].map(item => item.FileUrl)
                const Image2 = groupedData['2'].map(item => item.FileUrl)
                item.Details = [
                    { title: '过程', imageList: Image1, remark: groupedData['1'][0].Remark },
                    { title: '结果', imageList: Image2, remark: groupedData['2'][0].Remark },
                ]
                return item
            })
            setDetails(data)
        })
    })

    return (
        <div className="SecurityNewDetails">
            {Data && (
                <div className="mainTable">
                    <div className="Data">
                        <div className="Label">
                            <div>组织机构 : </div>
                            <div>{Data.OrganizationName}</div>
                        </div>
                        <div className="Label">
                            <div>隐患名称 : </div>
                            <div>{Data.Problem}</div>
                        </div>
                        <div className="Label">
                            <div>填报日期 : </div>
                            <div>{Data.SecurityDate}</div>
                        </div>
                        <div className="Label">
                            <div>隐患位置 : </div>
                            <div>{Data.TableName}</div>
                        </div>
                        <div className="Label">
                            <div>隐患等级 : </div>
                            <div>{Data.SecurityProblemTypeName}</div>
                        </div>
                        <div className="Label">
                            <div>治理时限 : </div>
                            <div>{Data.LimitDays}天</div>
                        </div>
                        <div className="Label">
                            <div>整改责任人 : </div>
                            <div>{Data.ResponsiblePersonName}</div>
                        </div>
                        <div className="Label">
                            <div>责任单位 : </div>
                            <div>{Data.ResponsibleDepartment}</div>
                        </div>
                        <div className="Label">
                            <div>验收人 : </div>
                            <div>{Data.AcceptancePersonName}</div>
                        </div>
                        <div className="Label">
                            <div>复查结果 : </div>
                            <div>{Data.ReCheckResult}</div>
                        </div>
                    </div>
                    <div className="Image">
                        {Data.children.map((item, index) => (
                            <Image key={index} src={item} />
                        ))}
                    </div>
                </div>
            )}
            {Details &&
                Details.map((item, index) => (
                    <div className="mainTable" key={index}>
                        <div className="Data">
                            <Divider>整改详情</Divider>
                            <div className="Label">
                                <div>整改时间 : </div>
                                <div>{item.CreateTime}</div>
                            </div>
                            <div className="Label">
                                <div>整改人员 : </div>
                                <div>{item.CreateUserName}</div>
                            </div>
                            <div className="Label">
                                <div>整改主题 : </div>
                                <div>{item.TableName}</div>
                            </div>
                            <div className="Label">
                                <div>整改描述 : </div>
                                <div>{item.Description}</div>
                            </div>
                            <div className="Label">
                                <div>整改过程 : </div>
                                <div>{item.Details[0].remark}</div>
                            </div>
                            <div className="Label">
                                <div>整改结果 : </div>
                                <div>{item.Details[1].remark}</div>
                            </div>
                        </div>
                        <div className="ImageArr">
                            {item.Details.map((data, key) => (
                                <div key={key}>
                                    <div>整改{data.title}</div>
                                    {data.imageList.map((url, i) => (
                                        <Image key={i} src={url} />
                                    ))}
                                </div>
                            ))}
                        </div>
                    </div>
                ))}
        </div>
    )
}

export const SecurityProcess = ({ data }) => {
    // getSecurityApprovalByUuid

    const [Data, setData] = useState()
    const { runAsync } = useRequest(Http, { manual: true })

    useMount(() => {
        runAsync({ url: 'getSecurityApprovalByUuid', data: { uuid: data.data.uuid } }).then(res => {
            const data = JSON.parse(
                JSON.stringify(res.list)
                    .replace(/flow/g, 'title')
                    .replace(/createTime/g, 'description'),
            )
            setData(data)
        })
    })

    return (
        <div className="SecurityProcess">
            {Data && <Steps progressDot current={Data.length - 1} direction="vertical" items={Data} />}
        </div>
    )
}

export const WeChatOfficialModel = ({ Off }) => {
    return (
        <div className="WeChatOfficialModel">
            <img src={WebCommonUrl + 'Common/WeChatOfficial_JT.jpg'} alt="" />
            <div>
                <div>使用微信扫一扫关注</div>
                <div>微信公众号</div>
                <div>接收消息推送</div>
            </div>
        </div>
    )
}

// 扫码登录
export const ScanCodeModel = ({ Off }) => {
    const [uuid] = useState(v4())

    const LoadingEvent = useEventEmitter()
    LoadingEvent.useSubscription(() => Off())

    useEffect(() => {
        const state = `${uuid}@${appid}@${client_id}@true`
        const get = `${API_LIST()['getCommonOpenUnionidOrTokenSSE']}?QRUuid=${uuid}&Type=token`
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid,
            scope: 'snsapi_login',
            response_type: 'code',
            redirect_uri: window.encodeURI(redirect_uri),
            state: state,
            style: 'black',
            href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
        }

        var eventSource = new EventSource(get)
        eventSource.onopen = () => new window.WxLogin(codeData)
        eventSource.onmessage = e => {
            const { data } = e
            if (data.length > 10) {
                const [token_type, access_token] = data.split(' ')
                LoginSignUpGetUserInfo({ token_type, access_token, login_type: undefined }, 2, LoadingEvent)
                Off()
            }
        }
        eventSource.onerror = () => eventSource.close()
        return () => {
            eventSource.close()
        }
    }, [uuid])
    return (
        <div className="WeChatBindBox">
            <div id="QRcode" />
        </div>
    )
}

// 微信绑定
export const WeChatBindBox = ({ Off }) => {
    const [uuid] = useState(v4())
    const [Loading, setLoading] = useState(true)
    const [BindState, setBindState] = useState(false)

    const { runAsync: posUuid } = useRequest(Http, { manual: true })
    const { runAsync: posUnBind } = useRequest(Http, { manual: true })

    const { runAsync: getState } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setBindState(!!!res.unionId)
            setLoading(false)
            if (!res.unionId) {
                const state = `${uuid}@${appid}@${client_id}`
                const get = `${API_LIST()['getOpenUnionidOrTokenSSE']}?QRUuid=${uuid}&Type=unionid`
                const codeData = {
                    self_redirect: true,
                    id: 'QRcode',
                    appid,
                    scope: 'snsapi_login',
                    response_type: 'code',
                    redirect_uri: window.encodeURI(redirect_uri),
                    state: state,
                    style: 'black',
                    href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
                }

                var eventSource = new EventSource(get)
                eventSource.onopen = () => new window.WxLogin(codeData)
                eventSource.onmessage = e => {
                    const { data } = e
                    if (data.length > 10) {
                        posUuid({ url: 'posBindOpenWeChatUnionIdAndUserId', data: { unionid: data } }).then(() => {
                            eventSource.close()
                            Off()
                        })
                    }
                }
                eventSource.onerror = () => eventSource.close()
            }
        },
    })

    useEffect(() => {
        const { userUuid } = JSON.parse(window.sessionStorage.getItem('UserInfo'))
        getState({ url: 'getUserID', path: [userUuid] })
    }, [uuid])

    const unBind = () => {
        posUnBind({ url: 'posUnBindOpenWeChatUnionId' }).then(() => {
            Off()
        })
    }

    return (
        <div className="WeChatBindBox">
            {Loading ? (
                '加载中'
            ) : BindState ? (
                <div id="QRcode" />
            ) : (
                <Result
                    status="warning"
                    title="是否要解除微信与帐号的绑定?"
                    extra={
                        <Button type="primary" key="console" danger onClick={unBind}>
                            解除绑定
                        </Button>
                    }
                />
            )}
        </div>
    )
}

// 附件
export const Annex = ({ data, Off }) => {
    const { url } = data
    const ImageBox = ({ url }) => <img src={url} alt={url} />
    const PdfBox = ({ url }) => <embed src={url} />
    const VideoBox = ({ url }) => (
        <Player fluid={false} width={'100%'} height={'100%'} playsInline src={url}>
            <BigPlayButton position="center" />
        </Player>
    )
    const OtherBox = () => <Result status="500" title="文件格式不支持预览" />
    const LiveVideo = ({ url }) => <LiveBox live={url} />

    const LiveFlv = ({ url }) => {
        const FlvBox = useRef()
        useEffect(() => {
            if (FlvBox) {
                var flvPlayer = flvjs.createPlayer({ type: 'flv', url })
                flvPlayer.attachMediaElement(FlvBox.current)
                flvPlayer.load()
                flvPlayer.play()
            }
        }, [FlvBox, url])
        return <video ref={FlvBox} className="FlvVideoBox" />
    }

    const [type, setType] = useState('ImageBox')
    const AttachmentList = { ImageBox, PdfBox, VideoBox, OtherBox, LiveVideo, LiveFlv }

    useEffect(() => {
        const regex = new RegExp(tripartiteList.join('|'), 'i')
        if (!url) setType('OtherBox')
        var suffix = url.substring(url.lastIndexOf('.') + 1).toLowerCase()
        if (regex.test(url)) {
            Off && Off()
            window.open(url)
        } else if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'jpeg') setType('ImageBox')
        else if (suffix === 'pdf') setType('PdfBox')
        else if (suffix === 'mp4') setType('VideoBox')
        else if (suffix === 'm3u8') setType('LiveVideo')
        else if (suffix === 'flv') setType('LiveFlv')
        else setType('OtherBox')
    }, [Off, url])

    return (
        <div className="Enclosure">
            {(() => {
                const Template = AttachmentList[type]
                return <Template url={url} />
            })()}
        </div>
    )
}

export const AnnexMore = ({ data }) => {
    const { list } = data.data
    const [OptionsCall, setOptionsCall] = useState()
    return (
        <div className="AnnexMore">
            {list.map(({ uuid, tableName, originalName, fileUrl }) => (
                <div
                    key={uuid}
                    onClick={() => {
                        setOptionsCall({ type: 'Annex', data: { url: fileUrl, title: tableName, width: '90vw' } })
                    }}
                >
                    {tableName || originalName}
                </div>
            ))}
            <ModalBox OptionsCall={OptionsCall} />
        </div>
    )
}
export const PrintQRcodeList = ({ data }) => {
    const { uuid: SampleItemUuid, displayNo } = data.data.record
    const [Source, setList] = useState()
    const [Image, setImage] = useState()
    const [PrintState, setPrintState] = useState(false)
    const UrlEvent = useEventEmitter()
    UrlEvent.useSubscription(val => setImage(val))
    useEffect(() => {
        const { testPieceNum, displayNo } = data.data.record
        setList([...new Array(testPieceNum).keys()].map(key => ({ uuid: key + 1, title: `${displayNo}-${key + 1}` })))
    }, [data])

    const onSave = num => saveAs(Image, `${displayNo}-${num}二维码.png`)
    const onPrint = () => {
        setPrintState(true)
        const [type, size, content, printDensity, printLabelType, printMode, count] =
            PrinterData(Image)['SampleParameter']
        initPrinter(type, size, content, printDensity, printLabelType, printMode, count, MarkEvent)
    }
    const MarkEvent = useEventEmitter()
    MarkEvent.useSubscription(() => setPrintState(false))

    return (
        <div className="PrintQRcodeList">
            {Source && (
                <List
                    dataSource={Source}
                    renderItem={({ uuid: num, title }) => (
                        <Popover content={<img src={Image} alt="" />}>
                            <List.Item
                                onMouseEnter={() => {
                                    PictureStream(
                                        API_LIST()['getLabSampleQRImage'],
                                        `SampleItemUuid=${SampleItemUuid}&num=${num}`,
                                        UrlEvent,
                                    )
                                }}
                                key={num}
                                extra={[
                                    <Button key="btn1" type="primary" onClick={() => onSave(num)}>
                                        下载二维码
                                    </Button>,
                                    <Button key="btn2" type="primary" onClick={() => onPrint(num)}>
                                        打印二维码
                                    </Button>,
                                ]}
                            >
                                <div className="PrintQRcodeList--Title">{title}</div>
                            </List.Item>
                        </Popover>
                    )}
                />
            )}
            {PrintState && (
                <div className="MarkBox">
                    <Loading
                        text="打印中..."
                        color={{ background: 'radial-gradient(rgba(0,0,0,0.7), rgba(255,255,255,1))' }}
                    />
                </div>
            )}
        </div>
    )
}

// 工建事务督办执行情况
export const EventListStatusModel = ({ data, actionRef, Off, ...config }) => {
    console.log(config)
    const { record } = data.data
    const [messageApi, contextHolder] = message.useMessage()
    const [endDate, setEndDate] = useState()
    const [evaluate, setEvaluate] = useState()
    const [eventStatus, setEventStatus] = useState()

    const [Loading, setLoading] = useState(false)

    useMount(() => {
        const { endDate, evaluate, eventStatus } = record
        setEndDate(endDate ? dayjs(endDate) : '')
        setEvaluate(evaluate)
        setEventStatus(eventStatus !== 1 ? eventStatus : '')
    })

    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: () => {
            messageApi.success('数据提交成功!')
            actionRef.current.reload()
            setTimeout(Off, 1500)
        },
    })

    const onSubmit = () => {
        setLoading(true)
        runAsync({ url: 'putEventList', data: { ...record, endDate, evaluate, eventStatus }, path: [record.uuid] })
    }

    return (
        <div className="EventListStatusModel">
            {contextHolder}
            <div>
                <div>
                    <div>事务状态 : </div>
                    <div>
                        <Select
                            placeholder="请选择事务状态"
                            value={eventStatus}
                            options={[
                                { value: 2, label: '完成' },
                                { value: 3, label: '无法完成' },
                            ]}
                            onChange={setEventStatus}
                        />
                    </div>
                </div>
                <div>
                    <div>完成日期 : </div>
                    <div>
                        <DatePicker value={endDate} onChange={setEndDate} />
                    </div>
                </div>
            </div>
            <div>
                <div>执行情况 : </div>
                <div>
                    <TextArea
                        placeholder="请填写执行情况"
                        value={evaluate}
                        onChange={e => setEvaluate(e.target.value)}
                    />
                </div>
            </div>
            <div>
                <Button type="primary" loading={Loading} onClick={onSubmit}>
                    提交保存
                </Button>
            </div>
        </div>
    )
}

// 打印试验二维码
export const PrintQRcode = ({ data }) => {
    const [PrintState, { setTrue: PrintTrue, setFalse: PrintFalse }] = useBoolean(false)
    const { data: record, url } = data
    const UrlEvent = useEventEmitter()
    const [Url, setUrl] = useState()
    useEffect(() => {
        setUrl(PictureStream(API_LIST()['getLabSampleQRImage'], `SampleItemUuid=${record.uuid}&num=1`, UrlEvent))
    }, [record, UrlEvent])
    UrlEvent.useSubscription(val => setUrl(val))
    const MarkEvent = useEventEmitter()
    MarkEvent.useSubscription(() => PrintFalse())
    return (
        <div className="codeBox">
            <img src={Url} alt="" />
            <div>
                <Button type="primary" size="large" onClick={() => saveAs(Url, '二维码.png')}>
                    下载二维码
                </Button>
                {url && (
                    <Button
                        type="primary"
                        size="large"
                        onClick={() => {
                            PrintTrue()
                            const [type, size, content, printDensity, printLabelType, printMode, count] =
                                PrinterData(Url)[url]
                            initPrinter(type, size, content, printDensity, printLabelType, printMode, count, MarkEvent)
                        }}
                    >
                        打印二维码
                    </Button>
                )}
            </div>
            {PrintState && (
                <div className="MarkBox">
                    <Loading
                        text="打印中..."
                        color={{ background: 'radial-gradient(rgba(0,0,0,0.7), rgba(255,255,255,1))' }}
                    />
                </div>
            )}
        </div>
    )
}

// 下载普通二维码
export const OrdinaryQRCode = ({ data }) => {
    const downloadQRCode = () => {
        const canvas = document.getElementById('myQRcode')?.querySelector('canvas')
        if (canvas) {
            const url = canvas.toDataURL()
            const a = document.createElement('a')
            a.download = 'QRCode.png'
            a.href = url
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        }
    }
    return (
        <div className="OrdinaryQRCode" id="myQRcode">
            <QRCode style={{ marginBottom: 16 }} size={552} iconSize={100} errorLevel="H" value={data.data.url} />
            <Button type="primary" onClick={downloadQRCode}>
                下载二维码
            </Button>
        </div>
    )
}

export const UrlQRCode = ({ data }) => {
    const { qrCodeImage, tableName } = data.data.record
    const Submit = () => {
        fetch(qrCodeImage)
            .then(response => response.blob())
            .then(blob => saveAs(blob, tableName + '.jpg'))
    }
    return (
        <div className="UrlQRCode">
            <img src={qrCodeImage} alt="" />
            <div className="Submit" onClick={Submit}>
                <Button type="primary">下载二维码</Button>
            </div>
        </div>
    )
}

// // 打开excel
// export const OpenExcel = ({ data }) => {
//     const [messageApi, contextHolder] = message.useMessage()
//     const [loading, setLoading] = useState(false)
//     const [ExcelName, setExcelName] = useState([])
//     const [spread, setSpread] = useState()
//     const [SaveStatus, setSaveStatus] = useState(false)
//     const [SubmitUrl, setSubmitUrl] = useState()
//     const [params, setParams] = useState()
//     const ExcelBox = useRef()
//     const saveExcel = () => {
//         const excelIo = new GC.Spread.Excel.IO()
//         excelIo.save(spread.toJSON(), e => saveAs(e, ExcelName))
//     }
//     const submitExcel = () => {
//         setLoading(true)
//         const { pos } = data.data
//         const excelIo = new GC.Spread.Excel.IO()
//         excelIo.save(spread.toJSON(), e => {
//             const forms = new FormData()
//             const { type } = e
//             const file = new File([e], ExcelName, { type })
//             forms.append('File', file)
//             forms.append('FileType', 3)
//             const urlSearchParams = new URLSearchParams(params)
//             const url = `${API_LIST()[pos || 'posSampleItemUploadTestDataEXCEL']}?` + urlSearchParams.toString()
//             axios.post(url, forms).then(() => messageApi.success('文件上传成功'))
//             setLoading(false)
//         })
//     }

//     useEffect(() => {
//         const { url, save, submit, pos, ...params } = data.data
//         const spread = new GC.Spread.Sheets.Workbook(ExcelBox.current, { sheetCount: 1 })
//         setSaveStatus(save)
//         setSubmitUrl(submit)
//         setSpread(spread)
//         setParams(params)

//         axios.get(API_LIST()[url], { params, responseType: 'blob' }).then(({ data, headers }) => {
//             let textName = ''
//             const nameArr = headers['content-disposition'].split(';')
//             nameArr.forEach(item => {
//                 if (item.indexOf("filename*=UTF-8''") !== -1) textName = decodeURI(item.split("filename*=UTF-8''")[1])
//             })
//             setExcelName(textName)
//             const excelIo = new GC.Spread.Excel.IO()
//             excelIo.open(data, workbookObj => {
//                 console.log(workbookObj)
//                 spread.fromJSON(workbookObj)
//             })
//         })
//     }, [data])

//     const onClick = () => {
//         // console.log(workbookObj)
//     }

//     return (
//         <div className="OpenExcel">
//             {contextHolder}
//             <div className="Excel" ref={ExcelBox} />
//             <div className="options">

//                 <Button onClick={onClick}>获取excelData</Button>

//                 {SaveStatus && <Button onClick={saveExcel}>下载Excel</Button>}
//                 {SubmitUrl && (
//                     <Button loading={loading} type="primary" onClick={submitExcel}>
//                         保存信息
//                     </Button>
//                 )}
//             </div>
//         </div>
//     )
// }

// 打开excel
export const OpenExcel = ({ data }) => {
    const testCode = {
        'af768c62-5ad6-43bd-8958-10dbce7a7669': {
            x: [
                [17, 5],
                [17, 7],
                [17, 9],
                [17, 11],
                [17, 13],
            ],
            y: [
                [9, 5],
                [9, 7],
                [9, 9],
                [9, 11],
                [9, 13],
            ],
            z: [
                [18, 5],
                [18, 13],
            ],
            p: [0, 18],
        },
        '89f3872d-c428-4865-a8f9-a80209f91897': {
            x: [
                [23, 3],
                [23, 7],
                [23, 10],
                [23, 14],
                [23, 18],
            ],
            y: [
                [14, 3],
                [14, 7],
                [14, 10],
                [14, 14],
                [14, 18],
            ],
            z: [
                [24, 3],
                [24, 18],
            ],
            p: [30, 0],
        },
    }
    const [messageApi, contextHolder] = message.useMessage()
    const [loading, setLoading] = useState(false)
    const [ExcelName, setExcelName] = useState([])
    const [spread, setSpread] = useState()
    const [SaveStatus, setSaveStatus] = useState(false)
    const [SubmitUrl, setSubmitUrl] = useState()
    const [params, setParams] = useState()
    const ExcelBox = useRef()
    const WorkBox = useRef()
    const saveExcel = () => {
        const excelIo = new GC.Spread.Excel.IO()
        excelIo.save(spread.toJSON(), e => saveAs(e, ExcelName))
    }
    const submitExcel = () => {
        setLoading(true)
        const { pos, path } = data.data
        const excelIo = new GC.Spread.Excel.IO()
        excelIo.save(spread.toJSON(), e => {
            const forms = new FormData()
            const { type } = e
            const file = new File([e], ExcelName, { type })
            forms.append('File', file)
            forms.append('FileType', 3)
            const urlSearchParams = new URLSearchParams(params)
            const url = `${API_LIST(path)[pos || 'posSampleItemUploadTestDataEXCEL']}?` + urlSearchParams.toString()
            axios.post(url, forms, { responseType: 'blob' }).then(res => {
                const excelIo = new GC.Spread.Excel.IO()
                excelIo.open(res.data, workBook => {
                    console.log(workBook)
                    spread.fromJSON(workBook)
                })
                messageApi.success('文件上传成功')
            })
            setLoading(false)
        })
    }
    useEffect(() => {
        const spread = new GC.Spread.Sheets.Workbook(WorkBox.current, { sheetCount: 1 })
        const { url, save, submit, pos, path, ...params } = data.data
        setSaveStatus(save)
        setSubmitUrl(submit)
        setSpread(spread)
        setParams(params)

        axios.get(API_LIST(path)[url], { params, responseType: 'blob' }).then(({ data, headers }) => {
            let textName = ''
            const nameArr = headers['content-disposition'].split(';')
            nameArr.forEach(item => {
                if (item.indexOf("filename*=UTF-8''") !== -1) textName = decodeURI(item.split("filename*=UTF-8''")[1])
            })
            setExcelName(textName)
            const excelIo = new GC.Spread.Excel.IO()
            excelIo.open(data, workbookObj => {
                spread.fromJSON(workbookObj)
            })
        })
        const config = {
            ribbon: { panels: [], ribbonHeight: 50 },
            contextMenu: [],
            fileMenu: 'fileMenuButton',
            sidePanels: [
                {
                    position: 'top',
                    allowResize: true,
                    command: 'formulaBarPanel',
                    uiTemplate: 'formulaBarTemplate',
                },
                {
                    position: 'bottom',
                    command: 'statusBarPanel',
                    uiTemplate: 'statusBarPanelTemplate',
                },
            ],
        }
        new GC.Spread.Sheets.Designer.Designer(ExcelBox.current, config, spread)
    }, [data])

    const { runAsync } = useRequest(Http, { manual: true })
    const onCount = () => {
        const sheet = spread.getActiveSheet()
        sheet.pictures.clear()
        sheet.shapes.remove('pic001')
        const { x, y, z, p } = testCode[data.data.TestTypeUuid]
        const X = x.map(item => {
            const [r, c] = item
            return sheet.getCell(r, c).value()
        })
        const Y = y.map(item => {
            const [r, c] = item
            return sheet.getCell(r, c).value()
        })
        let XValue = X.some(item => item === '' || item === null)
        let YValue = Y.some(item => item === '' || item === null)

        if (XValue || YValue) {
            message.error('数据不完整')
            return false
        }

        runAsync({
            url: 'getTextAllData',
            data: {
                x: X.join(','),
                y: Y.join(','),
                xLabel: '含水率',
                yLabel: '干密度',
                title: '含水率与干密度对应图表',
            },
        }).then(res => {
            const { img, x, y } = res
            z.forEach((item, index) => {
                const [r, c] = item
                sheet.setValue(r, c, index === 0 ? x : y)
            })
            const [r, c] = p
            const picture = sheet.pictures.add('pic001', img, 0, 0, 800, 800)
            picture.startRow(r)
            picture.startColumn(c)
            spread.getActiveSheet().invalidateLayout()
        })
    }

    return (
        <div className="OpenExcel">
            {contextHolder}
            <div className="Excel" ref={ExcelBox} />
            <div className="Work" ref={WorkBox} />
            <div className="options">
                {data.data.TestTypeUuid in testCode && <Button onClick={onCount}>计算</Button>}
                {SaveStatus && <Button onClick={saveExcel}>下载Excel</Button>}
                {SubmitUrl && (
                    <Button loading={loading} type="primary" onClick={submitExcel}>
                        保存信息
                    </Button>
                )}
            </div>
        </div>
    )
}

// 监控画面
export const MonitorVideo = ({ data }) => {
    const { runAsync } = useRequest(Http, { manual: true })
    const [VideoList, setVideoList] = useState([])
    useEffect(() => {
        const { url, ...props } = data.data
        runAsync({ url, data: props }).then(res => setVideoList(res.list))
    }, [data, runAsync])

    return (
        <div className="MonitorVideo">
            {VideoList.length !== 0 ? (
                <div className="SeeLabVideoModalScroll" style={{ width: VideoList?.length * 816 }}>
                    {VideoList.map((item, index) => (
                        <div key={index}>
                            {(() => {
                                const { cameraFactory, startTime, endTime } = item
                                if (cameraFactory === 1) {
                                    const begin = dayjs(startTime).format('YYYYMMDDHHmmss')
                                    const end = dayjs(endTime).format('YYYYMMDDHHmmss')
                                    return (
                                        <Video
                                            data={item}
                                            date={new Date().getTime()}
                                            playback={`&begin=${begin}&end=${end}`}
                                        />
                                    )
                                } else {
                                    return <DaHuaCameraPlayback data={item} />
                                }
                            })()}
                        </div>
                    ))}
                </div>
            ) : (
                <Result status="500" title="暂无监控数据" />
            )}
        </div>
    )
}

// 富文本编辑器
export const RichTextEditor = ({ data }) => {
    const [messageApi, contextHolder] = message.useMessage()
    const { record } = data.data
    const { uuid } = record
    const editorRef = useRef(null)
    const { runAsync: getData } = useRequest(Http, { manual: true })
    const { runAsync: putInfoManage } = useRequest(Http, { manual: true })
    const [loading, { setTrue, setFalse }] = useBoolean(false)

    const [initialValue, setInitialValue] = useState()

    useEffect(() => {
        getData({ url: 'getInfoManageGetOneInfoManage', data: { uuid } }).then(res => {
            const [{ infoContent }] = res
            setInitialValue(infoContent || '<p>请在这里输入文章内容.</p>')
        })
    }, [uuid, getData])

    const submit = () => {
        setTrue()
        const data = {
            ...record,
            infoContent: editorRef.current.getContent(),
        }
        putInfoManage({ url: 'putInfoManage', data, path: [uuid] }).then(res => {
            messageApi.success('内容保存成功过')
            setFalse()
        })
    }

    return (
        <div className="RichTextEditor">
            {contextHolder}
            <Editor
                apiKey="5b9brap9x1rvhy1ixyk6bzvxi3ensl97vz0q3g5pg3y88xfo"
                onInit={(_, editor) => (editorRef.current = editor)}
                initialValue={initialValue}
                init={{
                    language: 'zh_CN',
                    menubar: true,
                    branding: false,
                    automatic_uploads: true,
                }}
            />
            <Button type="primary" loading={loading} onClick={submit}>
                保存内容
            </Button>
        </div>
    )
}

// 中路的视频对讲
export const ZLVideoModal = ({ data, Off }) => {
    useEffect(() => {
        const initFlash = () => {
            const { swfobject } = window
            const { record, jsession } = data.data
            const { deviceSerial } = record
            if (
                typeof swfobject == 'undefined' ||
                swfobject.getObjectById('cmsv6flash') == null ||
                typeof swfobject.getObjectById('cmsv6flash').setWindowNum == 'undefined'
            )
                setTimeout(initFlash, 50)
            else {
                swfobject.getObjectById('cmsv6flash').setLanguage('cn.xml')
                swfobject.getObjectById('cmsv6flash').setWindowNum(40)
                swfobject.getObjectById('cmsv6flash').setWindowNum(1)
                swfobject.getObjectById('cmsv6flash').setServerInfo('cmsv.e-jt.cn', '6605')
                //停止播放视频
                swfobject.getObjectById('cmsv6flash').stopVideo(0)
                swfobject.getObjectById('cmsv6flash').setVideoInfo(0, 'vehicle1-CH1')
                swfobject.getObjectById('cmsv6flash').startVideo(0, jsession, deviceSerial, 0, 1, true)
                // swfobject.getObjectById('cmsv6flash').startListen(jsession, deviceSerial, 0, 'cmsv.e-jt.cn', '6605')
            }
        }
        var params = { lang: 'zh-cn' }
        ttxVideoAll.init('cmsv6flash', 952, 600, params, 'auto')
        initFlash()
    }, [data])

    const close = () => {
        const closeFunc = () => {
            const { swfobject } = window
            if (
                typeof swfobject == 'undefined' ||
                swfobject.getObjectById('cmsv6flash') == null ||
                typeof swfobject.getObjectById('cmsv6flash').setWindowNum == 'undefined'
            ) {
                setTimeout(closeFunc, 50)
            } else {
                swfobject.getObjectById('cmsv6flash').stopTalkback()
                swfobject.getObjectById('cmsv6flash').stopVideo(0)
                Off()
            }
        }
        closeFunc()
    }

    return (
        <div className="ZLVideoModal">
            <div id="cmsv6flash" />
            <div className="Button">
                <Button type="primary" onClick={close}>
                    停止对讲
                </Button>
            </div>
        </div>
    )
}

export const MonitoringModal = ({ data }) => {
    const { data: camera } = data
    return (
        <div className="MonitoringModal">
            <Video data={camera} />
        </div>
    )
}

const FileManagementType = {
    // 人员配置信息
    person: {
        API: {
            getUrl: 'getPersonAttachmentTypedAttachments',
            posUrl: 'posPersonAttachmentBatch',
            delUrl: 'delPersonAttachment',
        },

        ADDUrl: { url: 'getSecurityActivityPersonSecurityActivityList', path: 'uuid' },
        posPrame: { uuid: 'personUuid', attuuid: 'attachmentUuid', type: 'personAttachmentType' },
        infoItems: record => [
            { key: '1', label: '人员姓名', children: record.tableName },
            { key: '2', label: '人员类别', children: record.personTypeName },
            { key: '3', label: '组织机构', children: record.organizationName },

            { key: '4', label: '身份证', children: record.idCard },
            { key: '5', label: '手机号码', children: record.mobile },
            { key: '6', label: '年龄', children: record.age },
        ],
        DataMapping: {
            A01: '1',
            A02: '2',
            A03: '3',
            A04: '4',
            A05: '5',
            C01: '6',
            C02: '7',
            C03: '8',
            C04: '9',
            C05: '10',
            C06: '11',
            D01: '12',
            D03: '13',
        },
        ADDMapping: {
            B01: 'securityActivityList',
            B02: '2',
            B03: '3',
            B04: '4',
            D02: 'attendance',
            D04: 'wage',
        },
        DeleteMapping: ['A01', 'A02', 'A03', 'A04', 'A05', 'C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'D01', 'D03'],
        ApiList: {
            A01: { pos: '1', type: '1', valueFile: [1, 2, 3, 4, 5] },
            A02: { pos: '2', type: '2', valueFile: [1, 2, 3, 4, 5] },
            A03: { pos: '3', type: '3', valueFile: [1, 2, 3, 4, 5] },
            A04: { pos: '4', type: '4', valueFile: [1, 2, 3, 4, 5] },
            A05: { pos: '5', type: '5', valueFile: [1, 2, 3, 4, 5] },
            C01: { pos: '6', type: '6', valueFile: [1, 2, 3, 4, 5] },
            C02: { pos: '7', type: '7', valueFile: [1, 2, 3, 4, 5] },
            C03: { pos: '8', type: '8', valueFile: [1, 2, 3, 4, 5] },
            C04: { pos: '9', type: '9', valueFile: [1, 2, 3, 4, 5] },
            C05: { pos: '10', type: '10', valueFile: [1, 2, 3, 4, 5] },
            C06: { pos: '11', type: '11', valueFile: [1, 2, 3, 4, 5] },
            D01: { pos: '12', type: '12', valueFile: [1, 2, 3, 4, 5] },
            D03: { pos: '13', type: '13', valueFile: [1, 2, 3, 4, 5] },
        },
        items: [
            { key: 'A00', label: '人员相关信息' },
            { key: 'B00', label: '教育培训' },
            { key: 'C00', label: '告知、承诺、合同、协议等' },
            { key: 'D00', label: '考勤、工资等' },
        ],
        TabsOptions: {
            A00: [
                { key: 'A01', label: '身份证' },
                { key: 'A02', label: '体检表' },
                { key: 'A03', label: '用工协议' },
                { key: 'A04', label: '其他证件' },
                { key: 'A05', label: '进退场确认书' },
            ],
            B00: [
                { key: 'B01', label: '参加培训台账' },
                { key: 'B02', label: '培训考试试卷' },
                { key: 'B03', label: '培训评估表' },
                { key: 'B04', label: '安全技术交底' },
            ],
            C00: [
                {
                    key: 'C01',
                    label: '1.三级教育卡\n2.入场须知签字\n3.参加培训考试试卷\n4.参加安全技术交底台账\n5.岗位风险告知\n6.职业健康告知单\n7.个人安全承诺\n8.个人安全协议',
                },
            ],
            D00: [
                { key: 'D01', label: '技术交底台账' },
                { key: 'D02', label: '考勤表' },
                { key: 'D03', label: '请假申请' },
                { key: 'D04', label: '工资确认表' },
            ],
        },
        AddTemplate: { B01: 'Table', D02: 'Table', D04: 'Table' },
        columnsList: {
            B01: [
                { title: '组织机构', dataIndex: 'organizationName' },
                { title: '主题', dataIndex: 'tableName' },
                { title: '活动时长', dataIndex: 'interval' },
                { title: '状态', dataIndex: 'status' },
                { title: '开始时间', dataIndex: 'startTime' },
                { title: '结束时间', dataIndex: 'endTime' },
            ],
            D02: [
                { dataIndex: 'organizationName', title: '组织机构' },
                { dataIndex: 'attendanceTime', title: '考勤日期' },
            ],
            D04: [
                { dataIndex: 'organizationName', title: '组织机构', width: 200 },
                { dataIndex: 'laborCompany', title: '劳务公司', width: 200 },
                { dataIndex: 'personName', title: '姓名', width: 200 },
                { dataIndex: 'idCard', title: '身份证号', width: 200 },
                { dataIndex: 'creditCardNum', title: '银行卡号', width: 200 },
                { dataIndex: 'bankName', title: '开户委', width: 200 },
                { dataIndex: 'personTypeName', title: '岗位', width: 200 },
                { dataIndex: 'dailyWage', title: '日工资', width: 200 },
                { dataIndex: 'attendanceDayCount', title: '出勤工日', width: 200 },
                { dataIndex: 'wage', title: '实发工资', width: 200 },
                { dataIndex: 'beginTime', title: '开始日期', width: 200 },
                { dataIndex: 'endTime', title: '结束日期', width: 200 },
            ],
        },
    },
    // 机械配置信息
    machine: {
        API: {
            getUrl: 'getMachineAttachmentTypedAttachments',
            posUrl: 'posMachineAttachmentBatch',
            delUrl: 'delMachineAttachment',
        },
        ADDUrl: { url: 'getPersonAttachmentTypedAttachmentsByIdCard', path: 'driverIdentityCard' },

        posPrame: { uuid: 'machineUuid', attuuid: 'attachmentUuid', type: 'machineAttachmentType' },
        infoItems: record => [
            { key: '1', label: '机械名称', children: record.tableName },
            { key: '2', label: '进厂编号', children: record.code },
            { key: '3', label: '机械类别', children: record.machineTypeName },
            { key: '15', label: '车牌号', children: record.carNumber },
            { key: '5', label: '车主姓名', children: record.ownerName },
            { key: '6', label: '车主电话', children: record.ownerMobile },
            { key: '7', label: '司机姓名', children: record.driverName },
            { key: '8', label: '司机身份证', children: record.driverIdentityCard },
            { key: '9', label: '司机电话', children: record.driverMobile },
            { key: '4', label: '生产日期', children: record.manufactureDate },
            { key: '10', label: '进场时间', children: record.entryTime },
            { key: '11', label: '退场时间', children: record.leaveTime },
            { key: '12', label: '使用年限', children: record.durableYears },
            { key: '13', label: 'Gps设备序列号', children: record.gpsDeviceSerial },
            { key: '14', label: '摄像头名称', children: record.cameraName },
            { key: '16', label: '卡号', children: record.cardNumber },
        ],
        DataMapping: {
            A01: '1',
            A02: '2',
            A03: '3',
            A04: '4',
            A05: '5',
            A06: '6',
        },
        ADDMapping: {
            B01: '1',
            B02: '2',
            B03: '3',
            B04: '4',
            B05: '5',
        },
        DeleteMapping: ['A01', 'A02', 'A03', 'A04', 'A05', 'A06'],
        ApiList: {
            A01: { pos: '1', type: '1', valueFile: [1, 2, 3, 4, 5] },
            A02: { pos: '2', type: '2', valueFile: [1, 2, 3, 4, 5] },
            A03: { pos: '3', type: '3', valueFile: [1, 2, 3, 4, 5] },
            A04: { pos: '4', type: '4', valueFile: [1, 2, 3, 4, 5] },
            A05: { pos: '5', type: '5', valueFile: [1, 2, 3, 4, 5] },
            A06: { pos: '6', type: '6', valueFile: [1, 2, 3, 4, 5] },
        },
        items: [
            { key: 'A00', label: '机械信息' },
            { key: 'B00', label: '人员信息' },
        ],
        TabsOptions: {
            A00: [
                { key: 'A01', label: '机械照片' },
                { key: 'A02', label: '进出场记录表' },
                { key: 'A03', label: '验收记录表' },
                { key: 'A04', label: '维修记录表' },
                { key: 'A05', label: '保养记录表' },
                { key: 'A06', label: '档案记录表' },
            ],
            B00: [
                { key: 'B01', label: '身份证' },
                { key: 'B02', label: '体检表' },
                { key: 'B03', label: '用工协议' },
                { key: 'B04', label: '其他证件' },
                { key: 'B05', label: '进退场确认书' },
            ],
        },
        AddTemplate: {},
    },
}

// 人员档案 && 机械档案
export const FileManagement = ({ data }) => {
    const { record, classification, options } = data.data
    const { uuid, fileUrl } = record

    const {
        API,
        ADDUrl,
        posPrame,
        items,
        infoItems,
        DataMapping,
        ADDMapping,
        DeleteMapping,
        ApiList,
        TabsOptions,
        AddTemplate,
        columnsList,
    } = FileManagementType[classification]
    const { getUrl, posUrl, delUrl } = API

    const [TabsActive, setTabsActive] = useState('A00')
    const [LeftTabsActive, setLeftTabsActive] = useState('A01')

    const [Data, setData] = useState({})
    const [AddData, setAddData] = useState({})

    const { runAsync: getData } = useRequest(Http, { manual: true, onSuccess: res => setData(res) })
    const { runAsync: addData } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setAddData(res)
        },
    })
    const { runAsync: posData } = useRequest(Http, { manual: true })
    const { runAsync: delData } = useRequest(Http, { manual: true })

    const GetData = useCallback(() => {
        getData({ url: getUrl, path: [uuid] })
        if (ADDUrl) addData({ url: ADDUrl.url, data: {}, path: [record[ADDUrl.path]] })
    }, [getData, getUrl, uuid, ADDUrl, addData, record])

    const UploadEvent = useEventEmitter()
    UploadEvent.useSubscription(val => {
        const { type, uuidList } = val
        if (uuidList.length !== 0) {
            const data = uuidList.map(itme => ({
                [posPrame.uuid]: uuid,
                [posPrame.attuuid]: itme,
                [posPrame.type]: type,
            }))
            posData({ url: posUrl, data }).then(GetData)
        }
    })

    // 左侧通用Tabs
    const LeftTabs = ({ items }) => (
        <Tabs tabPosition="left" activeKey={LeftTabsActive} items={items} onChange={e => setLeftTabsActive(e)} />
    )

    const TabsTemplate = ({ items }) => {
        const [OptionsCall, setOptionsCall] = useState()
        const onOpen = e => {
            const { originalName, fileUrl } = e
            setOptionsCall({ type: 'Annex', data: { url: fileUrl, title: originalName, width: '90vw' } })
        }
        const onDelete = e => {
            delData({ url: delUrl, path: [e] }).then(() => GetData())
        }
        return (
            <>
                <LeftTabs items={items} />
                <div className="rightList">
                    {ApiList[LeftTabsActive]?.pos && !options && (
                        <IndependenceUpload
                            type={ApiList[LeftTabsActive].type}
                            valueFile={ApiList[LeftTabsActive].valueFile}
                            UploadEvent={UploadEvent}
                        />
                    )}
                    <div className="AnnexTemplate">
                        {(() => {
                            const DataOne = Data[DataMapping[LeftTabsActive]]
                            const DataTwo = AddData[ADDMapping[LeftTabsActive]]
                            const Template = ({ data }) => {
                                switch (AddTemplate[LeftTabsActive]) {
                                    case 'Table':
                                        if (data)
                                            return (
                                                <Table
                                                    columns={columnsList[LeftTabsActive]}
                                                    dataSource={data}
                                                    rowKey="uuid"
                                                    scroll={{ x: 500, y: 400 }}
                                                />
                                            )
                                        else return <Empty />
                                    default:
                                        return (
                                            <>
                                                {data.map(({ uuid, tableName, attachment }) => (
                                                    <div key={uuid} className="AnnexList">
                                                        <div onClick={() => onOpen(attachment)}>
                                                            {tableName && `${tableName} - `}
                                                            {attachment.originalName}
                                                        </div>
                                                        {DeleteMapping.includes(LeftTabsActive) && !options && (
                                                            <Popconfirm
                                                                title="是否确认删除附件"
                                                                onConfirm={() => onDelete(uuid)}
                                                                okText="删除"
                                                                cancelText="取消"
                                                            >
                                                                <Button type="link" danger>
                                                                    删除
                                                                </Button>
                                                            </Popconfirm>
                                                        )}
                                                    </div>
                                                ))}
                                            </>
                                        )
                                }
                            }
                            return DataOne || DataTwo ? <Template data={DataOne || DataTwo} /> : <Empty />
                        })()}
                        <ModalBox OptionsCall={OptionsCall} />
                    </div>
                </div>
            </>
        )
    }

    const onTabsChange = e => {
        setTabsActive(e)
        setLeftTabsActive(e[0] + '01')
    }

    useEffect(() => {
        GetData()
    }, [GetData])

    return (
        <div className="PersonFiles">
            <div className="base">
                {classification === 'person' && <Image width={200} height={200} src={fileUrl} fallback={fallback} />}
                <div className="info">
                    <Descriptions layout="vertical" items={infoItems(record)} />
                </div>
            </div>
            <div className="list">
                <Tabs activeKey={TabsActive} items={items} onChange={onTabsChange} />
                <div className="details">
                    <TabsTemplate items={TabsOptions[TabsActive]} />
                </div>
            </div>
        </div>
    )
}

export const SciencesDetails = ({ data }) => {
    const { uuid, tableName, organizationName, dictionaryName } = data.data.record

    const AnnexCon = {
        added: 'posScienceAttachments',
        initialValues: { scienceUuid: uuid },
        columns: [
            {
                title: 'scienceUuid',
                dataIndex: 'scienceUuid',
                valueType: 'hidden',
                hideInTable: true,
            },
            {
                dataIndex: 'attachmentUuid',
                title: '文件附件',
                valueType: 'upload',
                valueFile: [1, 2, 3, 4],
                fileUrl: 'fileUrl',
                rules: true,
                hideInTable: true,
            },
            {
                dataIndex: 'fileUrl',
                title: '文件附件',
                valueType: 'hidden',
                hideInSearch: true,
                hideInTable: true,
                hideInAdded: true,
                hideInModify: true,
                width: 400,
            },
        ],
    }
    const FlowCon = {
        added: 'posScienceDetails',
        initialValues: { scienceUuid: uuid },
        columns: [
            {
                title: '组织机构',
                dataIndex: 'scienceUuid',
                valueType: 'hidden',
                render: () => <div>{organizationName}</div>,
            },
            {
                title: '名称',
                dataIndex: 'tableName',
                valueType: 'input',
            },
            {
                title: '排序',
                dataIndex: 'sortId',
                valueType: 'inputNumber',
            },
            {
                title: '计划日期',
                dataIndex: 'planTime',
                valueType: 'Date',
            },
            {
                title: '完成日期',
                dataIndex: 'finishTime',
                valueType: 'Date',
            },
            {
                title: '操作',
                valueType: 'systemOperation',
                fixed: 'right',
                hideInSearch: true,
                hideInAdded: true,
                hideInModify: true,
                render: ({ uuid }) => {
                    return [
                        <Popconfirm
                            title="删除流程"
                            description="是否删除该流程?"
                            onConfirm={() => onDeleteFlow(uuid)}
                            okText="删除"
                            cancelText="取消"
                        >
                            <Button danger type="link">
                                删除
                            </Button>
                        </Popconfirm>,
                    ]
                },
            },
        ],
    }

    const [Annex, setAnnex] = useState([])
    const [Flow, setFlow] = useState([])

    const [OptionsCall, setOptionsCall] = useState()
    const [configure, setConfigure] = useState()

    const { runAsync: getAnnex } = useRequest(Http, {
        manual: true,
        onSuccess: res => setAnnex(res.list),
    })

    const { runAsync: getFlow } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            console.log('流程', res)
            setFlow(res.list)
        },
    })

    const { runAsync: DelAnnex } = useRequest(Http, {
        manual: true,
        onSuccess: res => getAnnex({ url: 'getScienceAttachments', data: { scienceUuid: uuid } }),
    })

    const { runAsync: DelFlow } = useRequest(Http, {
        manual: true,
        onSuccess: res => getFlow({ url: 'getScienceDetails', data: { scienceUuid: uuid } }),
    })

    useEffect(() => {
        getAnnex({ url: 'getScienceAttachments', data: { scienceUuid: uuid } })
        getFlow({ url: 'getScienceDetails', data: { scienceUuid: uuid } })
    }, [getAnnex, getFlow, uuid])

    const items = [
        { key: 1, label: '组织机构', children: organizationName },
        { key: 2, label: '名称', children: tableName },
        { key: 3, label: '类别', children: dictionaryName },
    ]

    const AddAnnex = () => {
        setConfigure(AnnexCon)
        setOptionsCall({ type: 'Add', data: { title: '添加附件' } })
    }
    const AddFlow = () => {
        setConfigure(FlowCon)
        setOptionsCall({ type: 'Add', data: { title: '添加附件' } })
    }

    const reloadEvent = useEventEmitter()
    reloadEvent.useSubscription(val => {
        getAnnex({ url: 'getScienceAttachments', data: { scienceUuid: uuid } })
        getFlow({ url: 'getScienceDetails', data: { scienceUuid: uuid } })
    })

    const onOpenAnnex = url => {
        setOptionsCall({ type: 'Annex', data: { title: '查看附件', url } })
    }

    const onDeleteAnnex = uuid => {
        DelAnnex({ url: 'delScienceAttachments', path: [uuid] })
    }

    const onDeleteFlow = uuid => {
        DelFlow({ url: 'delScienceDetails', path: [uuid] })
    }

    return (
        <div className="SciencesDetails">
            <Descriptions items={items} />
            <div className="Details">
                <div className="Annex">
                    <div className="Title">
                        <div>附件详情</div>
                        <Button type="primary" onClick={AddAnnex}>
                            添加
                        </Button>
                    </div>
                    <div className="Item">
                        {Annex.map(({ uuid, fileUrl, originalName }) => (
                            <div className="Annexitem" key={uuid}>
                                <div onClick={() => onOpenAnnex(fileUrl)}>{originalName}</div>
                                <Popconfirm
                                    title="附件删除"
                                    description="是否删除该附件?"
                                    onConfirm={() => onDeleteAnnex(uuid)}
                                    okText="删除"
                                    cancelText="取消"
                                >
                                    <Button danger type="link">
                                        删除
                                    </Button>
                                </Popconfirm>
                            </div>
                        ))}
                    </div>
                </div>
                <div className="Flow ">
                    <div className="Title">
                        <div>流程详情</div>
                        <Button type="primary" onClick={AddFlow}>
                            添加
                        </Button>
                    </div>
                    <div className="Item">
                        <Table columns={FlowCon.columns} dataSource={Flow} rowKey="uuid" scroll={{ y: 400 }} />
                    </div>
                </div>
            </div>
            <ModalBox OptionsCall={OptionsCall} configure={configure} reloadEvent={reloadEvent} />
        </div>
    )
}

// AnonymousSecurityAnnex
export const AnonymousSecurityAnnex = ({ data }) => {
    const { anonymousSecurityAttachments } = data.data.record

    console.log(anonymousSecurityAttachments)
    return (
        <div className="AnonymousSecurityAnnex">
            {anonymousSecurityAttachments.length !== 0 ? (
                <div className="ImageList">
                    {anonymousSecurityAttachments.map(({ uuid, attachment }) => (
                        <img key={uuid} alt={uuid} src={attachment.fileUrl} />
                    ))}
                </div>
            ) : (
                <Empty />
            )}
        </div>
    )
}
